package com.gene.controller.content;

import com.aliyun.oss.OSSClient;
import com.gene.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created by lenovo on 2018/1/15.
 */
@Controller
@RequestMapping("/gene-safe")
public class ContentUpload {

    /**
     * 内容的图片上传
     * @return
     */
    @RequestMapping(value = "/content/Upload",method = RequestMethod.POST)
    @ResponseBody
    public ResultData itemUpload(@RequestParam(value="file",required=false)MultipartFile[] file) throws  Exception{
        ResultData result=new ResultData();
        OSSClient ossClient = AliyunOSSClientUtil.getOSSClient();
        String files="";
        try {
            for (MultipartFile mult:file){
                String originalImageName = mult.getOriginalFilename();
                String suffix = originalImageName.substring(originalImageName.lastIndexOf(".") + 1);
                String imageName = ImageUtil.getImageName(GenerationIdUtils.generateShortUuid(), suffix);
                String folder = AliyunOSSClientUtil.createCurrentFolder(ossClient,OSSClientConstants.BACKET_NAME,OSSClientConstants.CONTENTS);
                AliyunOSSClientUtil.createObject(ossClient, OSSClientConstants.BACKET_NAME,folder+imageName, mult.getInputStream());
                files+=folder+imageName+",";
            }
            result.setErrorCode(CodeValue.SUCCESS);
            result.setMsg(MsgValue.SUCCESS);
            result.setData(new StringBuffer(files).deleteCharAt(files.length()-1));//图片路径
            return result;
        }catch (Exception e){
            throw new RuntimeException("服务器繁忙，上传图片失败");
        }finally {
            ossClient.shutdown();
        }

    }
}
